package cc.rengu.redp.bizimpl.igas.controller;


import cc.rengu.redp.bizimpl.bean.LabelValueBean;
import cc.rengu.redp.bizimpl.enums.BizDataStatusEnum;
import cc.rengu.redp.bizimpl.enums.IgasYesOrNoEnum;
import cc.rengu.redp.bizimpl.enums.PageOptFlagEnum;
import cc.rengu.redp.bizimpl.enums.SettleAccTypeEnum;
import cc.rengu.redp.bizimpl.igas.domain.PSrcChannelInfo;
import cc.rengu.redp.bizimpl.igas.domain.PSrcTxnAuthCfg;
import cc.rengu.redp.bizimpl.igas.domain.PTxnCfg;
import cc.rengu.redp.bizimpl.igas.service.PSrcChannelInfoService;
import cc.rengu.redp.bizimpl.igas.service.PSrcTxnAuthCfgService;
import cc.rengu.redp.bizimpl.igas.service.PTxnCfgService;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.DateUtils;
import cc.rengu.redp.common.annotation.Log;
import cc.rengu.redp.common.controller.BaseController;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 刘玉亮.LL
 * @since 2021-06-08
 */
@Slf4j
@Api(tags = "产品管理:交易渠道信息管理")
@RestController
@RequestMapping("/admin/igas/pSrcChannelInfo")
public class PSrcChannelInfoController extends BaseController {
    @Autowired
    private PSrcChannelInfoService pSrcChannelInfoService;

    @Autowired
    private PSrcTxnAuthCfgService pSrcTxnAuthCfgService;
    @Autowired
    private PTxnCfgService pTxnCfgService;

    @GetMapping
//    @RequiresPermissions("areaInfo:view")
    public Map<String, Object> list(QueryRequest request, PSrcChannelInfo entity) {
        return getDataTable(this.pSrcChannelInfoService.findByPage(request, entity));
    }

    @Log("编辑查询")
    @GetMapping(value = "/edit")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "instId", value = "机构标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "srcChannelId", value = "通道标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "transChannelId", value = "交易渠道标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "optFlag", value = "操作类型：新增、修改、删除、审核等", required = true, dataType = "String")
    })
    public Map<String, Object> getEdit(@NotBlank(message = "{required}") String srcChannelId, @NotBlank(message = "{required}") String instId
            , @NotBlank(message = "{required}") String optFlag, @NotBlank(message = "{required}") String transChannelId) throws RedpException {
        HashMap<String, Object> result = new HashMap<>();
        PSrcChannelInfo entity = new PSrcChannelInfo();
        List<LabelValueBean> accTypes = Lists.newArrayList();
        accTypes.add(new LabelValueBean(SettleAccTypeEnum.INNER_DEBIT_ACCOUNT.getDesc(), SettleAccTypeEnum.INNER_DEBIT_ACCOUNT.getType()));
        accTypes.add(new LabelValueBean(SettleAccTypeEnum.INNER_CREDIT_ACCOUNT.getDesc(), SettleAccTypeEnum.INNER_CREDIT_ACCOUNT.getType()));
        accTypes.add(new LabelValueBean(SettleAccTypeEnum.INNER_BANKBOOK.getDesc(), SettleAccTypeEnum.INNER_BANKBOOK.getType()));
        accTypes.add(new LabelValueBean(SettleAccTypeEnum.INNER_INTERNAL_ACCOUNT.getDesc(), SettleAccTypeEnum.INNER_INTERNAL_ACCOUNT.getType()));
        accTypes.add(new LabelValueBean(SettleAccTypeEnum.INNER_PUBLIC_ACCOUNT.getDesc(), SettleAccTypeEnum.INNER_PUBLIC_ACCOUNT.getType()));
        accTypes.add(new LabelValueBean(SettleAccTypeEnum.OTHER_DEBIT_ACCOUNT.getDesc(), SettleAccTypeEnum.OTHER_DEBIT_ACCOUNT.getType()));
        accTypes.add(new LabelValueBean(SettleAccTypeEnum.OTHER_CREDIT_ACCOUNT.getDesc(), SettleAccTypeEnum.OTHER_CREDIT_ACCOUNT.getType()));
        accTypes.add(new LabelValueBean(SettleAccTypeEnum.OTHER_BANKBOOK.getDesc(), SettleAccTypeEnum.OTHER_BANKBOOK.getType()));
        accTypes.add(new LabelValueBean(SettleAccTypeEnum.OTHER_INTERNAL_ACCOUNT.getDesc(), SettleAccTypeEnum.OTHER_INTERNAL_ACCOUNT.getType()));
        accTypes.add(new LabelValueBean(SettleAccTypeEnum.OTHER_PUBLIC_ACCOUNT.getDesc(), SettleAccTypeEnum.OTHER_PUBLIC_ACCOUNT.getType()));
        accTypes.add(new LabelValueBean(SettleAccTypeEnum.ALL_ACCOUNT.getDesc(), SettleAccTypeEnum.ALL_ACCOUNT.getType()));
        result.put("accTypes", accTypes);
        List<PTxnCfg> allTxnList = pTxnCfgService.findPTxnCfgByList(null, null, null, null);
        Map<String, String> allTxnMap = Maps.newHashMap();
        if (Common.isNotBlank(allTxnList)) {
            Iterator<PTxnCfg> it = allTxnList.iterator();
            while (it.hasNext()) {
                PTxnCfg pTxnCfg = it.next();
                allTxnMap.put(pTxnCfg.getTxnNum(), pTxnCfg.getTxnName());
            }
            result.put("allTxn", allTxnMap);
        }

        if (PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(optFlag)) {//由于这几个字段是必填，这里预先赋值否则录入界面因为隐藏输入域而无法通过非空校验

            entity.setTransChannelStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
            entity.setCreateTime(DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS"));
            entity.setInstId(instId);

        } else if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(optFlag)) {//审核查询显示临时表数据，转换成对应实体
            log.error("不支持审核操作!");
            throw new RedpException("不支持审核操作！");
        } else {
            entity = this.getOne(instId, srcChannelId, transChannelId);
            if (Common.isBlank(entity)) {
                log.error("根据唯一索引没有找到指定数据！");
                throw new RedpException("根据唯一索引没有找到指定数据！");
            } else {
                List<String> supportedAcctTypes = Lists.newArrayList();
                if ("*".equals(entity.getSupportAcctType())) {
                    String type = SettleAccTypeEnum.ALL_ACCOUNT.getType();
                    supportedAcctTypes.add(SettleAccTypeEnum.ALL_ACCOUNT.getType());
                } else if (Common.isNotBlank(entity.getSupportAcctType()) && entity.getSupportAcctType().length() >= 10) {

                    String[] acctypes = entity.getSupportAcctType().split("");
                    for (int i = 0; i < 10; i++) {
                        if (IgasYesOrNoEnum.Yes.getType().equals(acctypes[i])) {
                            supportedAcctTypes.add(accTypes.get(i).getValue());
                        }
                    }
                } else {
                    log.info("entity.getSupportAcctType() 值长度为{}，不符合规范", null == entity.getSupportAcctType() ? 0 : entity.getSupportAcctType().length());
                }
                entity.setSupportAcctTypeList(supportedAcctTypes);
            }
            //获取渠道支持的交易
            List<PSrcTxnAuthCfg> srcTxns = Lists.newArrayList();
            List<String> surpportTxns = Lists.newArrayList();
            srcTxns = pSrcTxnAuthCfgService.findPSrcTxnAuthCfgByList(entity.getInstId(), entity.getSrcChannelId(), entity.getTransChannelId(), null, null);
            if (Common.isNotBlank(srcTxns)) {
                Iterator<PSrcTxnAuthCfg> it = srcTxns.iterator();
                while (it.hasNext()) {
                    PSrcTxnAuthCfg pSrcTxnAuthCfg = it.next();
                    surpportTxns.add(pSrcTxnAuthCfg.getTxnNum());
                }
            }
            entity.setSurportTxnList(surpportTxns);
        }
        entity.setOptFlag(optFlag);
        result.put("entity", entity);
        result.put("optFlag", optFlag);
        return result;
    }

    @Log("查询单条")
    @GetMapping(value = "/getOne")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "instId", value = "机构标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "transChannelId", value = "交易渠道标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "srcChannelId", value = "通道标识", required = true, dataType = "String")
    })
    public PSrcChannelInfo getOne(@NotBlank(message = "{required}") String instId, @NotBlank(message = "{required}") String srcChannelId, @NotBlank(message = "{required}") String transChannelId) {
        LambdaQueryWrapper<PSrcChannelInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PSrcChannelInfo::getInstId, instId);
        wrapper.eq(PSrcChannelInfo::getSrcChannelId, srcChannelId);
        wrapper.eq(PSrcChannelInfo::getTransChannelId, transChannelId);
        return pSrcChannelInfoService.getOne(wrapper);
    }


    @Log("修改")
    @PutMapping("/update")
//    @RequiresPermissions("areaInfo:update")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "instId", value = "机构标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "srcChannelId", value = "渠道标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "optFlag", value = "操作类型：新增、修改、删除、审核等", required = true, dataType = "String")
    })
    public void update(@Valid PSrcChannelInfo entity) throws RedpException {
        try {
            this.pSrcChannelInfoService.update(entity);
        } catch (Exception e) {
            String message = "修改失败";
            log.error(message, e);
            throw new RedpException(message);
        }
    }

    @Log("停用")
    @PutMapping("/transChannelStatus")
//    @RequiresPermissions("areaInfo:update")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "instId", value = "机构标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "srcChannelId", value = "渠道标识", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "optFlag", value = "操作类型：新增、修改、删除、审核等", required = true, dataType = "String")
    })
    public void updateStatus(@Valid PSrcChannelInfo entity) throws RedpException {
        try {
            this.pSrcChannelInfoService.updateStatus(entity);
        } catch (Exception e) {
            String message = "修改失败";
            log.error(message, e);
            throw new RedpException(message);
        }
    }

    //重写list
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        //设置数组最大长度
        binder.setAutoGrowCollectionLimit(1024);
    }
}